"""
YAML 解析工具
"""
import yaml
import json
from typing import Dict, Any


def json_to_yaml(json_data: Dict[str, Any]) -> str:
    """
    将 JSON 数据转换为 YAML 格式字符串

    Args:
        json_data: JSON 格式的字典数据

    Returns:
        YAML 格式的字符串
    """
    return yaml.dump(json_data, allow_unicode=True, default_flow_style=False, sort_keys=False)


def yaml_to_json(yaml_content: str) -> Dict[str, Any]:
    """
    将 YAML 字符串转换为 JSON 数据

    Args:
        yaml_content: YAML 格式的字符串

    Returns:
        JSON 格式的字典数据
    """
    return yaml.safe_load(yaml_content)


def validate_yaml(yaml_content: str) -> tuple[bool, str]:
    """
    验证 YAML 格式是否正确

    Args:
        yaml_content: YAML 格式的字符串

    Returns:
        (是否有效, 错误信息)
    """
    try:
        yaml.safe_load(yaml_content)
        return True, ""
    except yaml.YAMLError as e:
        return False, str(e)


def validate_experiment_template(config: Dict[str, Any]) -> tuple[bool, str]:
    """
    验证实验模板配置的必填字段

    Args:
        config: 实验模板配置字典

    Returns:
        (是否有效, 错误信息)
    """
    # 必填字段
    required_fields = ["name", "config"]

    for field in required_fields:
        if field not in config or not config[field]:
            return False, f"缺少必填字段: {field}"

    # 验证 config 中的必填字段
    if "params" not in config["config"] or not config["config"]["params"]:
        return False, "缺少必填字段: config.params"

    if "userCommand" not in config["config"] or not config["config"]["userCommand"]:
        return False, "缺少必填字段: config.userCommand"

    return True, ""
